package org.bite.lesson11;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo1106 {
    public static void main(String[] args) throws InterruptedException {
        Counter1106 counter = new Counter1106();

        // 创建两个线程对一个变量进时累加
        Thread t1 = new Thread(() -> {
            // 5万次
            for (int i = 0; i < 50000; i++) {
                // 加读锁
                counter.increase();
                //加写锁
                //counter.increase1();
            }
        });

        // 线程2
        Thread t2 = new Thread(() -> {
            // 5万次
            for (int i = 0; i < 50000; i++) {
                // 加读锁
                counter.increase();
                // 加写锁
                //counter.increase1();
            }
        });

        // 启动线程
        t1.start();
        t2.start();

        // 等待线程执行完成
        t1.join();
        t2.join();

        // 查看运行结果
        System.out.println("count = " + counter.count);
    }
}
class Counter1106{
    public volatile int count = 0;
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    /**
     * 加读锁
     * 存在线程安全问题，不是排他锁
     */
    public void increase() {
        ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        try{
            readLock.lock();
            count++;
        }finally{
            readLock.unlock();
        }
    }
    /**
     * 加写锁
     */
    public void increase1() {
        ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
        try{
            writeLock.lock();
            count++;
        }finally{
            writeLock.unlock();
        }
    }
}
